package com.cxy.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @ClassName: Server
 * @Description: TODO(BIO通信的服务端)
 * @author 菜徐鸭
 * @date 2020年5月9日
 *
 */
public class Server {
	
	private static class ServerTask implements Runnable {

		private Socket socket = null;

		public ServerTask(Socket socket) {
			this.socket = socket;
		}

		public void run() {
			// 和客户端通讯的输入输出流
			try (ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
					ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())) {
				// 服务器的输入
				String userName = inputStream.readUTF();
				System.out.println("接受到客户端消息：" + userName);
				// 输出流
				outputStream.writeUTF("hello," + userName);
				outputStream.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					socket.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}

		}

	}
	
	public static void main(String[] args) throws IOException {
		//服务器必备
		ServerSocket serverSocket=new ServerSocket();
		//绑定监听端口
		serverSocket.bind(new InetSocketAddress(10001));
		System.out.println("服务启动......");
		while (true) {
			new Thread(new ServerTask(serverSocket.accept())).start();
			
		}
	}
}